package com.xxx.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author blijojo
 * @date 2021/5/20
 */
@RestController
@Slf4j
public class UserController {


    @Value("${server.port}")
    private int port;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/user")
    public String invokeDemo() {
        log.info("调用user服务,服务端口:{}", port);
        //1.方式一: 使用RestTemplate写url
//        RestTemplate restTemplate = new RestTemplate();
//        String result = restTemplate.getForObject("http://localhost:8888/order", String.class);
//        return "user调用order服务,返回值:" + result;
        //2.方式二: 使用DiscoveryClient获取服务实例列表
//        List<ServiceInstance> instances = discoveryClient.getInstances("order-client");
//        instances.forEach(serviceInstance -> {
//            log.info("服务主机:{}, 服务端口:{}, 服务地址:{}",serviceInstance.getHost(),serviceInstance.getPort(),serviceInstance.getUri());
//        });
//        String result = new RestTemplate().getForObject(instances.get(0).getUri() + "/order", String.class);
//        return "user调用order服务,返回值:" + result;
        //3.方式三: 使用LoadBalancerClient负载均衡获取服务实例
//        ServiceInstance instance = loadBalancerClient.choose("order-client");
//        log.info("服务主机:{}, 服务端口:{}, 服务地址:{}", instance.getHost(), instance.getPort(), instance.getUri());
//        String result = new RestTemplate().getForObject(instance.getUri() + "/order", String.class);
//        return "user调用order服务,返回值:" + result;
        //4.方式四: 使用@LoadBalanced注解
        String result = restTemplate.getForObject("http://order-client/order", String.class);
        return "user调用order服务,返回值:" + result;
    }

}
